package com.xing.lei.happy.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@SuppressWarnings("unchecked")
public class OrderedMap<K, V> extends HashMap<K, V> {
	private static final long serialVersionUID = 1L;
	private Chain<K> chain;

	@Override
	public V put(K key, V value) {
		Chain<K> chain = new Chain<K>(key);
		if (this.chain != null) {
			this.chain.next(chain);
		}
		this.chain = chain;
		return super.put(key, value);
	}

	public List<K> keys() {
		int size = this.size();
		Object[] ks = new Object[size];
		Chain<K> chain = this.chain;
		Set<K> set = null;
		while (chain != null) {
			K k = chain.value();
			if (set == null) {
				set = new HashSet(keySet());
			}
			if (set.remove(k)) {
				ks[--size] = k;
			}
			chain = chain.prev();
		}
		return ArrayUtils.toList(ks);
	}

	@Override
	public Collection<V> values() {
		List<V> list = new ArrayList<V>();
		for (K key : keys()) {
			list.add(get(key));
		}
		return list;
	}

	@Override
	public void clear() {
		super.clear();
		chain = null;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder("{");
		for (K key : keys()) {
			sb.append(key).append("=").append(get(key)).append(", ");
		}
		return StringUtils.subtail(sb.toString(), 2) + "}";
	}
}